package com.free.solon.common.exception;

import com.free.solon.common.model.R;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;
import org.noear.solon.validation.ValidatorException;

/**
 * 全局异常处理
 *
 * @Author: hao.ding@insentek.com
 * @Date: 2024/5/21 10:02
 */
@Component
public class AppRouterInterceptor implements RouterInterceptor {
    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        try {
            chain.doIntercept(ctx, mainHandler);
        } catch (BusinessException e) {
            ctx.render(R.failure(500, e.getMessage()));
        } catch (ValidatorException e) {
            ctx.render(R.failure(e.getCode(), e.getMessage()));
        } catch (Throwable e) {
            ctx.render(R.failure(500, "系统异常"));
        }
    }
}
